<template>
  <div class="wid">
      <div class="tables">
          <div class="categoryWrap">
            <div class="serchLeft">
                <div>
                    <span>姓名 : </span>
                    <el-input
                        placeholder="请输入姓名"
                        prefix-icon="el-icon-search"
                        v-model.trim="headFrom.name" @input="serchList">
                    </el-input>
                </div>
                <div>
                    <span>工号 : </span>
                    <el-input
                        placeholder="请输入工号"
                        prefix-icon="el-icon-search"
                        v-model.trim="headFrom.number" @input="serchList">
                    </el-input>
                </div>
            </div>
            <div class="operatingBtn">
                <el-button type="primary" @click="addRows">新增</el-button>
                <el-button type="danger"  @click="deleRows">删除</el-button>
            </div>
          </div>
          <el-table :header-cell-style="{background:'#f5f6f8'}"
            ref="multipleTable"
            :data="tableData"
            tooltip-effect="dark"
            style="width: 100%"
            @selection-change="handleSelectionChange">
            <el-table-column
            type="selection"
           >
            </el-table-column>
            <el-table-column
               label="序号"
            >
            <template slot-scope="scope">{{ scope.row.index }}</template>
            </el-table-column>
            <el-table-column
               label="姓名"
            >
            <template slot-scope="scope">{{ scope.row.username }}</template>
            </el-table-column>
            <el-table-column
            prop="number"
            label="工号"
            >
            </el-table-column>
            <el-table-column
            prop="department.name"
            label="部门"
            
             >
            </el-table-column>
             <el-table-column
            prop="position.name"
            label="岗位"
           
             >
            </el-table-column>
             <el-table-column
            prop="phone"
            label="手机号"
           
             >
            </el-table-column>
            <el-table-column
            prop="email"
            label="邮箱"
           
             >
            </el-table-column>
             <el-table-column
            prop="status1"
            label="状态"
           
             >
            </el-table-column>
             <!-- <el-table-column
            prop="grade"
            label="等级"
           
             >
            </el-table-column> -->
            <el-table-column
            prop="create_time"
            label="创建时间"
             >
            </el-table-column>
            <el-table-column
            prop="job_status1"
            label="在职状态"
             >
            </el-table-column>
            <el-table-column
            prop="operation"
            label="操作"
             >
            <template slot-scope="scope">
                <el-button
                    @click.native.prevent="editRow(scope.$index, tableData)"
                    type="primary"
                    size="mini ">
                    编辑
                </el-button>
                <el-button v-if="scope.row.status == 1"
                    @click.native.prevent="forbidden(scope.$index, tableData)"
                    type="info"
                    size="mini ">
                  禁用
                </el-button>
                <el-button v-else
                    @click.native.prevent="openRows(scope.$index, tableData)"
                    type="danger"
                    size="mini ">
                  启用
                </el-button>
            </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="page">
            <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            layout="sizes, prev, pager, next"
            :total="pageList.total">
            </el-pagination>
        </div>
      </div>
            <!-- hide-on-single-page -->

      <!-- 新增 -->
      <el-dialog :visible.sync="dialogFormVisible" title="基本信息" @close='closeDialog'>
            <div class="topButton">
                <el-button @click="authShow = true">权限修改</el-button>
                <el-button type="primary" @click="editPassWord  = true ">密码修改</el-button>
            </div>
            <el-form  label-width="130px"  :model="ruleForm" :inline="true" :rules="rules" ref="ruleForm"> 
                <el-row type="flex" justify="space-between">
                    <el-col :span="12">
                        <el-form-item label="姓名：" prop="username">
                            <el-input v-model="ruleForm.username"   autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="部门：" prop="department_id">
                           <!-- <el-cascader 
                           @change="handleChange()"
                           v-model="value"
                           :props="{ checkStrictly: true }"
                           :options="region" 
                           clearable ></el-cascader> -->
                           
                           <el-cascader 
                            v-model="ruleForm.department_id" 
                            @change="handleChange()"
                            :options="region" 
                            style="width:100%"
                            :props="{checkStrictly: true}"
                            >
                            </el-cascader>
                        </el-form-item>
                        <el-form-item label="状态：" prop="job_status">
                           <el-select v-model="ruleForm.job_status"  placeholder="请选择">
                                <el-option 
                                v-for="item in WorkingStateList"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="编号：" v-if="ruleForm.id">
                            <el-input disabled v-model="ruleForm.number"  autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="邮箱：" prop="email">
                            <el-input v-model="ruleForm.email"   autocomplete="off"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="员工账号：" prop="phone">
                            <el-input v-model="ruleForm.phone"   autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="岗位：" prop="position_id">
                            <el-select v-model="ruleForm.position_id"  placeholder="请选择">
                                <el-option 
                                    v-for="(item,i) in positionList"
                                    :key="i"
                                    :label="item.label"
                                    :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <!-- <el-form-item label="等级：" v-if="ruleForm.id">
                            <el-input v-model="form.categoryNumber"  autocomplete="off"></el-input>
                        </el-form-item> -->
                         <el-form-item label="创建时间：" v-if="ruleForm.id">
                            <el-date-picker 
                            readonly
                               @change="changeDate()"
                                v-model="create_time"
                                type="date"
                                placeholder="选择日期">
                            </el-date-picker>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="submit()">确 定</el-button>
            </div>
     </el-dialog>
     <!-- 重置密码 -->
     <el-dialog :visible.sync="editPassWord" title="重置密码" class="password_dialog">
         <div slot="footer" class="dialog-footer">
             <el-form :model="passWordForm">
                 <el-form-item label="账号" >
                    <el-input disabled  v-model="passWordForm.phone" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="新密码" >
                    <el-input clearable  show-password   type="passWord" v-model.trim="passWordForm.newPassword" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <el-button @click="editPassWord = false">取 消</el-button>
            <el-button type="primary" @click="changePassword()">确 定</el-button>
        </div>
     </el-dialog>
  </div>
</template>

<script>
  export default {
    data () {
      return {
          ruleForm:{
              username:'',
              department_id:'',
              position_id:'',
              phone:'',
              job_status:'',
              id:'',
              email:'',
          },
          rules: {
            username: [
                { required: true, message: '请输入姓名', trigger: 'blur' },
            ],
            department_id: [
                { required: true, message: '请选择部门', trigger: 'blur' },
            ],
            position_id: [
                { required: true, message: '请选择岗位', trigger: 'blur' },
            ],
            phone: [
                { required: true, message: '请输入员工账号', trigger: 'blur' },
                { min: 3,max: 11, message: '不于11位', trigger: 'blur' }
            ],
            job_status: [
                { required: true, message: '请选择状态', trigger: 'blur' },
            ],
            email: [
                { required: true, message: '请输入邮箱', trigger: 'blur' },
            ],
          },
          value:'',
          region: [],
          headFrom:{
            name:'',
            number:'',
            page:1
          },
          positionList:[],
          passWordForm:{
              phone:'',
              newPassword:''
          },
          authShow:false,
          editPassWord:false,
          dialogFormVisible:false,
          serchTxt:'',
          multipleSelection:[],
          branch:"",
          WorkingStateList:[
              {
                value: '0',
                label: '离职'
              },
              {
                value: '1',
                label: '在职'
              },
          ],
          time:'',
          tableData:[],
          currentPage: 1,
          totalPage:0,
          timer:0,
          page:1,
          pageList:{},
          create_time:''
      };
    },
    mounted() {
        this.getUser()
        this.getDepartment()
    },
    methods: {
        //重置员工密码 
        async changePassword(){
            if(!this.passWordForm.newPassword){
                this.utils.message("密码不能为空！")
                return false
            }
            let { code, data } = await this.$Http.resetPwd({id:this.ruleForm.id,pwd:this.passWordForm.newPassword});
            if (code == 10000) {
               this.utils.message("密码重置成功")
               this.editPassWord = false
            }
        },
        // 关闭弹窗清空input内容
        closeDialog(){
            this.headFrom= this.$options.data().headFrom;
        },
        // 搜索
        serchList(){
            if(this.timer) {
                clearTimeout(this.timer);
            }
            this.timer = setTimeout(() => {
                this.getUser(1)
            }, 1000);
        },
        handleChange(value){
            // if(this.value){
            //     console.log(this.value,"this.value");
            //     this.ruleForm.department_id = this.value.pop()
            // }
            // 通过部门id获取岗位列表
            this.ruleForm.position_id = '';
            this.getPosition()
        },
        // 获取部门列表
        async getDepartment() {
            let { code, data } = await this.$Http.getDepartment();
            if (code == 10000) {
               this.region = this.asd(data||[]);
               console.log(this.region,"this.region");
            }
        },
        //遍历部门列表
        asd(list,ids){
          return list.map((v,i)=>{
             v.label = v.name;
             v.value = v.id;
                ids?v.department_id = [...ids,v.id]:v.department_id=[v.id]
             if(v.child&&v.child.length){
                v.children = this.asd(v.child,v.department_id);
                delete v.child;
              }else delete v.child;
              return v;
          })
        },
        // 获取岗位列表
        async getPosition() {
             let {department_id} = this.ruleForm;
             console.log(department_id,"@@@@");
             if(!department_id.length)return;
            //  this.ruleForm.department_id = department_id[department_id.length-1];
            let params={
                department_id:department_id[department_id.length-1],
                is_all:1
            }
            this.positionList=[]
            let { code, data } = await this.$Http.getPosition(params);
            if (code == 10000) {
                
                if(data.length){
                    data.forEach(ele=>{
                        let obj= {
                            value: ele.id,
                            label: ele.name
                        }
                        this.positionList.push(obj)
                    })
                }else{
                    this.positionList=[]
                }
                this.currentPage  = data.current_page
                this.totalPage  = data.total
            }
        },
        // 获取员工列表
         async  getUser(type,limits){
            let params = {
                page:this.page,
                limit:limits
            }
            if(type == 1){
                params = this.headFrom
            }
             this.utils.isLoadding(true)
            let { code, data } = await this.$Http.getUser(params);
             this.utils.isLoadding(false)
            if (code == 10000) {
                data.data.forEach((ele,index)=>{
                    ele.index = index+1
                    ele.job_status1 = ele.job_status == 0 ? "离职" :'在职'
                    ele.status1 = ele.status == 0 ? "禁用中" :'启用中'
                })
                this.tableData = data.data
                 this.pageList = data
            }
        },
        // 提交
         submit(){
            this.$refs.ruleForm.validate(async (valid) => {
                if (valid) {
                    this.utils.isLoadding(true)
                    let {department_id} =this.ruleForm;
                    this.ruleForm.department_id = department_id[department_id.length-1]
                    let { code, data } = await this.$Http.setUser(this.ruleForm);
                    this.utils.isLoadding(false)
                    if (code == 10000) {
                        this.utils.message("提交成功")
                        this.dialogFormVisible = false
                        this.getUser()
                        // 初始状态
                        this.headFrom= this.$options.data().headFrom;
                    }
                }
            })
        },
        recursion2(list,id){
            let str = '';
            for (let i of list) {
               if(i.id==id){
                   str =  i.department_id
                   break;
               }
               if(i.children) str = this.recursion2(i.children,id)
            }
            return str
        },
        // 编辑
        editRow(index,table){
            this.ruleForm.id = this.tableData[index].id
            this.dialogFormVisible = true
            let {username, department_id,position_id,phone,job_status,email,create_time,number} = this.tableData[index]
            this.ruleForm.username = username
            this.value = department_id;
            this.ruleForm.department_id = this.recursion2(this.region,department_id)
            this.ruleForm.position_id = Number(position_id)
            this.ruleForm.phone = phone
            this.ruleForm.job_status =String(job_status)
            this.ruleForm.email = email
            this.ruleForm.number = number
            this.create_time = create_time
            this.passWordForm.phone = phone;
            this.getPosition();
        },
        // 新增
        addRows(){
            this.ruleForm.id = ""
            this.dialogFormVisible = true
        },
        // 禁用
         forbidden(index){
             let id = this.tableData[index].id
            this.$confirm('此操作将禁用员工信息，是否继续？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(async () => {
                    let { code, data } =  await this.$Http.disableUser({id:id,status:0});
                    if (code == 10000) {
                        this.utils.message("禁用成功","suc")
                        this.tableData[index].status = 0
                        this.tableData[index].status1 = "禁用中"
                    }
                }).catch(() => {
                this.xin.message("您已取消","info")         
            });
        },
        // 启用
        openRows(index){
             let id = this.tableData[index].id
             this.$confirm('此操作将开启，是否继续？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(async() => {
                    let { code, data } = await this.$Http.disableUser({id:id,status:1});
                    if (code == 10000) {
                         this.utils.message("成功开启","suc")
                         this.tableData[index].status = 1
                         this.tableData[index].status1 = "启用中"
                    }
                }).catch(() => {
                this.xin.message("您已取消","info")         
            });
        },
        // 批量删除操作
        deleRows(){
            if(!this.multipleSelection.length){
                this.utils.message("请勾选要删除的员工信息!");
                return false;
            }
            let ids = []
            this.multipleSelection.forEach(ele=>{
                ids.push(ele.id)
            })
            this.$confirm('此操作将永久删除员工信息，是否继续？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
                }).then(async () => {
                    let { code, data } = await this.$Http.delUser({id:ids.join(',')});
                    if (code == 10000) {
                        console.log(111111111111)
                        this.utils.message("删除成功","suc")
                        this.getUser()
                    }
                }).catch(() => {
                this.xin.message("您已取消","info")         
            });
        },
        // 侧边栏选择
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        //分页事件   
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
             this.getUser(3,val)
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.page = val
            this.getUser()
        }
    },

  }

</script>
<style lang='scss' scoped>
.wid{
    width: 100%;
    padding: 20px;
    box-sizing: border-box;
    background: #F5F5F5;
    .topButton{
        position: absolute;
        right: 20px;
        top: 20px;
    }
    .categoryWrap{
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 15px 20px;
        box-sizing: border-box;
        .serchLeft{
            width: 80%;
            display: flex;
            align-items: center;
            >div:nth-child(1){
                margin-right: 30px;
            }
            span{
                color: #333;
                font-size: 16px;
                margin-right: 20px;
            }
            .el-input{
                width: 300px;
            }
            .el-input__inner{
                border: none;
                background: #f5f5f5;
            }
        }
        .operatingBtn{
            display: flex;
            margin: 0 5px;
            align-items: center;
        }
    
    }
    .placeholder{
        width: 100%;
        height: 10px;
        background: #fff;
    }
    .crumbs{
        padding: 10px 5px;
        color: #666;
        font-size: 16px;
        background: #fff;
        margin-bottom: 20px;
    }
    .tables{
        background: #fff;
        min-height: calc(100vh - 130px);
        border-radius: 12px;
    }
    .page{
        width: 510px;
        margin: 20px auto 0;
    }
}
    ::v-deep.el-form-item{
        display: flex;
    }

    ::v-deep.el-input{
        width: 200px;
    }
    ::v-deep.el-form-item__content{
        margin-left: 0 !important;
    }
    ::v-deep.el-form-item{
        .el-form-item__label{
            width: 90px ;
        }
    }
    ::v-deep.el-form{
        margin: 50px 0 20px 0;
    }
   .password_dialog{
        ::v-deep.el-form{
            margin: 0px 0 0px 0;
        }
    } 
   ::v-deep.dialog-footer{
       margin-top: -40px;
   }
</style>